package org.ehe.business.overdue.service.ove;

import lombok.extern.slf4j.Slf4j;
import org.ehe.business.overdue.config.OverdueStatus;
import org.ehe.business.overdue.handler.OverdueHandler;
import org.ehe.business.overdue.service.ove.OverdueDelayService;
import org.ehe.business.overdue.util.FormatOverdueTimeUtil;
import org.ehe.business.timeout.contants.BizTypeConstant;
import org.ehe.common.sse.dto.SseMessageDto;
import org.ehe.common.sse.utils.SseMessageUtils;
import org.ehe.erp.domain.purchase.ErpPurchaseOrder;
import org.ehe.erp.mapper.purchase.ErpPurchaseOrderMapper;
import org.ehe.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 采购超期处理实现
 * @author :zhangnn
 * @className :ProcurementOverdueService
 * @description: TODO
 * @date 2025-07-29 16:19:23
 */

@Service
@Slf4j
public class ProcurementOverdueService implements OverdueHandler {

    @Autowired
    private ErpPurchaseOrderMapper purchaseOrderMapper;

    @Autowired
    private ScheduledExecutorService scheduledExecutorService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private OverdueDelayService overdueDelayService;

    @Override
    public String getBizType() {
        return "purchaseOrderOverdue";
    }

    @Override
    public void handleOverdue(Long bizId) {
        try {
            log.info("开始处理采购订单响应超时: orderId={}", bizId);
            // 1. 更新项目状态
            ErpPurchaseOrder order = purchaseOrderMapper.selectById(bizId);
            //未执行超期
            if(order.getIsOverdue().equals(OverdueStatus.PENDING)){
                //超期未处理
                order.setIsOverdue(OverdueStatus.OVERDUE_AND_PENDING);
            }
            purchaseOrderMapper.updateById(order);
            // 2. 发送通知
            sendOverdueNotification(order);
            // 3. 再次进行超期监听延时1小时
            overdueDelayService.delay(BizTypeConstant.PURCHASEORDER+"Overdue",bizId);
        } catch (Exception e) {
            log.error("处理项目超期失败: projectId={}", bizId, e);
        }
    }

    /**
     * 超期前提醒操作
     * @param bizId 业务ID
     */
    @Override
    public void remindBeforeOverdue(Long bizId) {
        ErpPurchaseOrder order = purchaseOrderMapper.selectById(bizId);
        //状态变更
        overdueDelayService.remind(BizTypeConstant.PURCHASEORDER+"Overdue",bizId);
        //提醒
        scheduledExecutorService.schedule(() -> {
            try {
                SseMessageDto dto = new SseMessageDto();
                dto.setMessage("采购订单【No."+ order.getNo()+"-"+order.getName()+"】仅剩余30分钟，请及时处理！");

                List<Long> ids = userService.queryUserIds();
                dto.setUserIds(ids);

                dto.setMessageType("REMIND");
                SseMessageUtils.publishMessage(dto);
                log.info("项目超期通知发送成功: purchaseOrderId={}", order.getId());
            } catch (Exception e) {
                log.error("发送项目超期通知失败: purchaseOrderId={}", order.getId(), e);
            }
        }, 4, TimeUnit.SECONDS);
    }


    /**
     * 发送超期通知
     */
    private void sendOverdueNotification(ErpPurchaseOrder order) {
        scheduledExecutorService.schedule(() -> {
            try {
                String overdueTime = FormatOverdueTimeUtil.formatOverdueTime(order.getIsOverdueEndTime());
                SseMessageDto dto = new SseMessageDto();
                dto.setMessage("采购订单【No."+ order.getNo()+"-"+order.getName()+"】已超期"+overdueTime+"，请及时处理！");

                List<Long> ids = userService.queryUserIds();
                dto.setUserIds(ids);

                dto.setMessageType("OVERDUE_NOTIFICATION");
                SseMessageUtils.publishMessage(dto);
                log.info("项目超期通知发送成功: solutionId={}", order.getId());
            } catch (Exception e) {
                log.error("发送项目超期通知失败: solutionId={}", order.getId(), e);
            }
        }, 5, TimeUnit.SECONDS);
    }
}
